package com.smart.campus.web.controller.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.smart.campus.common.core.controller.BaseController;
import com.smart.campus.common.core.domain.AjaxResult;
import com.smart.campus.common.utils.DateUtils;
import com.smart.campus.common.utils.security.Md5Utils;
import com.smart.campus.framework.web.service.DictService;
import com.smart.campus.school.domain.*;
import com.smart.campus.school.domain.query.IllegalRecordQuery;
import com.smart.campus.school.domain.request.ApiLoginRequest;
import com.smart.campus.school.domain.vo.*;
import com.smart.campus.school.domain.vo.api.*;
import com.smart.campus.school.service.*;
import com.smart.campus.system.domain.SysDept;
import com.smart.campus.system.domain.SysDictData;
import com.smart.campus.system.domain.SysNotice;
import com.smart.campus.system.domain.SysUser;
import com.smart.campus.system.service.ISysDeptService;
import com.smart.campus.system.service.ISysNoticeService;
import com.smart.campus.system.service.ISysUserService;
import com.smart.campus.system.utils.DictUtils;
import com.smart.campus.web.core.config.WxMaConfiguration;
import com.smart.campus.web.utils.SchoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.Collator;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.smart.campus.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;

/**
 * 外部apiController
 * 
 * @author Zhihe.Li
 * @date 2020-05-18
 */
@Controller
@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping("/api")
@Slf4j
public class ApiLoginController extends BaseController
{
    private String prefix = "api";

    @Autowired
    private IMsgService msgService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IClassInfoService classInfoService;

    @Autowired
    private ISysNoticeService noticeService;


    @Autowired
    private IAppConfigService appConfigService;
    @Autowired
    IStudentService studentService;

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private DictService dictService;

    @Autowired
    ICourseMainConfigService courseMainConfigService;
    @Autowired
    ICourseItemConfigService courseItemConfigService;
    @Autowired
    IGradeService gradeService;

    @Autowired
    IExamRoomScheduleService examRoomScheduleService;
    @Autowired
    IExamRoomClassesService examRoomClassesService;
    @Autowired
    IExamRoomStudentsService examRoomStudentsService;

    @Autowired
    IClockInRecordService clockInRecordService;

    @Autowired
    IApplyListService applyListService;//请假接口

    @Autowired
    IIllegalRecordService illegalRecordService;

    @Autowired
    private IScBadgeService badgeService;
    @Autowired
    private ISchoolExtService schoolExtService;

    @Autowired
    private IAttendanceRecordService attendanceRecordService;

    @Autowired
    IWisdomService wisdomService;
    @Autowired
    private IAdjustCourseService adjustCourseService;
    @Autowired
    private IPersonnelInfoService personnelInfoService;
    @Autowired
    private ICourseItemTimeService courseItemTimeService;
    @Autowired
    private IAppVersionService appVersionService;

    @Autowired
    private ICalzzCommitteeService calzzCommitteeService;
    @Autowired
    private IDutyTableService dutyTableService;
    @GetMapping("/login")
    @ResponseBody
    public AjaxResult login(ApiLoginRequest request, HttpServletRequest httpServletRequest)
    {
        AjaxResult res = AjaxResult.success();
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(request.getClassId()) || StringUtils.isEmpty(request.getPassword()))
        {
            return AjaxResult.error("班级编号或密码为空");
        }
        String token = Md5Utils.hash(request.getClassId()+"#123456");
        if(!token.equals(request.getPassword())){
            return AjaxResult.error("密码错误");
        }
        ClassInfo classInfo= classInfoService.login(request.getClassId(),request.getPassword());
        // 用户名或密码为空 错误
        if (classInfo ==  null)
        {
            return AjaxResult.error("班级编号错误");
        }
//        httpServletRequest.getSession().setAttribute("classInfo",classInfo);
        SysUser user = userService.selectUserById(classInfo.getTeacherId());
        SysDept dept = deptService.selectDeptById(classInfo.getDeptId());
        Grade grade = gradeService.selectGradeById(classInfo.getGradeId());
        ClassInfoApiVo classI = new ClassInfoApiVo();
        classI.setId(classInfo.getId());
        classI.setGradeId(classInfo.getGradeId());
        classI.setClassName(classInfo.getClassName());
        classI.setGradeName(classInfo.getGradeName());
        classI.setTeacherId(classInfo.getTeacherId());
        if(grade!=null){
            classI.setGradeName(grade.getGradeName());
        }
        if(dept!=null){
            classI.setSchoolName(dept.getDeptName());
        }
        if(user!=null){
            UserInfoApiVo userInfoApiVo = new UserInfoApiVo();
            userInfoApiVo.setUserId(user.getUserId());
            userInfoApiVo.setUserName(user.getUserName());
            userInfoApiVo.setAvatar(user.getAvatar());
            userInfoApiVo.setDesc(user.getRemark());
            classI.setUser(userInfoApiVo);
        }
        Student student = new Student();
        student.setClassId(classInfo.getId());
        List<Student> list = studentService.selectStudentList(student);
        if(list!=null){
            classI.setStudentCount(list.size());
        }
        Wisdom wiItem = new Wisdom();
        wiItem.setClassId(classInfo.getId());
        List<Wisdom> wisdomList = wisdomService.selectWisdomList(wiItem);
        if(wisdomList!=null&&!wisdomList.isEmpty()){
            classI.setWisdomList(wisdomList);
        }
        res.put("classInfo",classI);
        return res;
    }

    @GetMapping("/getStudents")
@ResponseBody
public AjaxResult getStudents(ApiLoginRequest request)
{
    AjaxResult res = null;
    String classId = request.getClassId();
    if(classId!=null){
        ClassInfo classInfo = classInfoService.selectClassInfoById(Long.parseLong(classId));
        if(classInfo!=null){
            res = AjaxResult.success();
            Student student = new Student();
            student.setClassId(classInfo.getId());
            List<Student> list = studentService.selectStudentList(student);
            List<StudentApiVo> list2 = new ArrayList<>();
            if(list!=null){
                for (Student stu:list
                ) {
                    StudentApiVo uvo = new StudentApiVo();
                    uvo.setUserId(stu.getId());
                    uvo.setUserName(stu.getStudentName());
                    uvo.setAvatar(stu.getImg());
                    uvo.setExamCode(stu.getExamCode());
                    uvo.setHobbies(stu.getHobbies());
                    uvo.setMotto(stu.getMotto());
                    uvo.setTarget(stu.getTarget());
                    list2.add(uvo);
                }
            }
            res.put("students",list2);
        }
    }else{
        return AjaxResult.error("请重新登陆");
    }
    return res;
}

    @GetMapping("/getTeachers")
    @ResponseBody
    public AjaxResult getTeachers(ApiLoginRequest request)
    {
        AjaxResult res = null;
        String classId = request.getClassId();
        if(classId!=null){
            ClassInfo classInfo = classInfoService.selectClassInfoById(Long.parseLong(classId));
            if(classInfo!=null){
                res = AjaxResult.success();
                SysUser teacher = new SysUser();
                teacher.setDeptId(classInfo.getDeptId());
                List<SysUser> list = userService.selectUserList(teacher);
                Long schoolId = classInfo.getDeptId();
                CourseMainConfigVo conf = new CourseMainConfigVo();
                conf.setBgDate(DateUtils.getNowDate());
                conf.setGradeId(classInfo.getGradeId());
                //后期需要添加学校Id区分各个学校的课程
                conf.setSchoolId(schoolId);
                List<TeacherApiVo> list2 = new ArrayList<TeacherApiVo>();
                CourseMainConfigVo mainc = courseMainConfigService.selectCourseMainConfigItem(conf);
                if(mainc!=null){
                    int wk = DateUtils.getWeeksSubByCurr(mainc.getBgDate());
                    int circle = mainc.getWeeks();
                    CourseItemConfigVo item = new CourseItemConfigVo();
                    item.setMainId(mainc.getId());
                    int type = 1;
                    circle = circle==0?1:circle;
                    if(circle != 1){
                        type = wk%circle;
                        if(type==0){
                            type = circle;
                        }
                    }
                    item.setType(type);
                    item.setClazzId(classInfo.getId());
//                    item.setWeek(DateUtils.getCurrWeerk());//获取全部的任课教师
                    List<CourseItemConfigVo> listCourse = courseItemConfigService.selectCourseItemConfigList(item);
                    for (CourseItemConfigVo item2: listCourse) {
                        Long tid = item2.getTeacherId();
                        if(tid!=null){
                            SysUser u = findUserInfo(tid, list);
                            TeacherApiVo tvo = new TeacherApiVo();
                            tvo.setUserId(u.getUserId());
                            tvo.setUserName(u.getUserName());
                            tvo.setAvatar(u.getAvatar());
                            tvo.setDesc(u.getRemark());
                            tvo.setCourseId(item2.getCourseId());
                            SysDictData c = findCourseInfo(item2.getCourseId());
                            if(c!=null){
                                tvo.setCourseName(c.getDictLabel());
                            }
                            if(!list2.contains(tvo)){
                                list2.add(tvo);
                            }
                        }
                    }
                }
                res.put("teachers",list2);
            }
        }else{
            return AjaxResult.error("请重新登陆");
        }
        return res;
    }

    @GetMapping("/getNotices")
    @ResponseBody
    public AjaxResult getNotices(ApiLoginRequest request)
    {
        AjaxResult res = AjaxResult.success();
        String classId = request.getClassId();
        if(classId!=null){
            ClassInfo classInfo = classInfoService.selectClassInfoById(Long.parseLong(classId));
            if(classInfo!=null){
                Long schoolId = classInfo.getDeptId();
                SysNotice notice = new SysNotice();
                notice.setSchoolId(schoolId);
                List<SysNotice> list = noticeService.selectNoticeList(notice);
                res.put("notice",list);
            }
        }else{
            return AjaxResult.error("请重新登陆");
        }
        return res;
    }

    /**
     * 微信端获取新闻公告列表
     * @return
     */
    @GetMapping("/getNoticeList")
    @ResponseBody
    public AjaxResult getNoticeList(Long userId)
    {

        if(userId == null){
            return AjaxResult.error("请登录后再操作");
        }
        SysUser user = userService.selectUserById(userId);
        SysNotice notice = new SysNotice();
        notice.setSchoolId(SchoolUtil.getSchoolId(user.getDept()));

        List<SysNotice> list = noticeService.selectNoticeList(notice);

        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询公告成功",list);

        return res;
    }
    /**
     * 微信端获取新闻公告详情
     * @return
     */
    @GetMapping("/getNoticeById")
    @ResponseBody
    public AjaxResult getNoticeById(String id)
    {

        SysNotice notice = this.noticeService.selectNoticeById(Long.parseLong(id));
        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询公告详情成功",notice);

        return res;
    }

    /**
     * 获取课程信息
     * @param request
     * @return
     */
    @GetMapping("/getCourses")
    @ResponseBody
    public AjaxResult getCourses(ApiLoginRequest request)
    {
        AjaxResult res = AjaxResult.success();
        String classId = request.getClassId();
        if(classId!=null){
            ClassInfo classInfo =classInfoService.selectClassInfoById(Long.parseLong(classId));
            if(classInfo!=null){
            Long schoolId = classInfo.getDeptId();
            CourseMainConfigVo conf = new CourseMainConfigVo();
            conf.setBgDate(DateUtils.getNowDate());
            conf.setGradeId(classInfo.getGradeId());
            //后期需要添加学校Id区分各个学校的课程
            conf.setSchoolId(schoolId);
            CourseMainConfigVo mainc = courseMainConfigService.selectCourseMainConfigItem(conf);
            if(mainc!=null){
                int wk = DateUtils.getWeeksSubByCurr(mainc.getBgDate());
                int circle = mainc.getWeeks();
                CourseItemConfigVo item = new CourseItemConfigVo();
                item.setMainId(mainc.getId());
                int type = 1;
                circle = circle==0?1:circle;
                if(circle != 1){
                    type = wk%circle;
                    if(type==0){
                        type = circle;
                    }
                }
                item.setType(type);
                item.setClazzId(classInfo.getId());
                item.setWeek(DateUtils.getCurrWeerk());
                List<CourseItemConfigVo> list = courseItemConfigService.selectCourseItemConfigList(item);
                List<CourseApiVo> list2 = new ArrayList<>();
                int sections = mainc.getSections();
                SysUser user = new SysUser();
                user.setDeptId(schoolId);
                List<SysUser> uList = userService.selectUserList(user);
                if(list!=null){
                    for(int i=1;i<=sections;i++){
                        CourseApiVo cvo = getCourseInfoBySection(i,list,uList);
                        list2.add(cvo);
                    }
//                    for (CourseItemConfigVo item0:list ) {
//                        CourseApiVo cvo = new CourseApiVo();
//                        cvo.setSection(item0.getSection());
//                        SysDictData d0 = findCourseInfo(item0.getCourseId());
//                        if(d0!=null){
//                            item0.setCourseName(d0.getDictLabel());
//                            cvo.setCourseName(d0.getDictLabel());
//                        }
//                        if(item0.getTeacherId()!=null){
//                            user = findUserInfo(item0.getTeacherId(),uList);
//                            if(user!=null){
//                                item0.setTeacherName(user.getUserName());
//                                cvo.setTeacherName(user.getUserName());
//                                cvo.setAvatar(user.getAvatar());
//                            }
//                        }
//                        if(!StringUtils.isEmpty(item0.getBTime())){
//                            cvo.setBTime(item0.getBTime());
//                            cvo.setETime(item0.getETime());
//                            cvo.makeTime();
//                        }
//                        list2.add(cvo);
//                    }

                }else{
                    for(int i=1;i<=sections;i++){
                        CourseApiVo cvo = getCourseInfoBySection(i,null,uList);
                        list2.add(cvo);
                    }
                }
                res.put("courseList",list2);
            }
            res.put("courseConfig",mainc);
            }
        }else{
            return AjaxResult.error("请重新登陆");
        }
        return res;
    }

    /**
     * 获取周课程信息
     * @param request
     * @return
     */
    @GetMapping("/getWeekCourses")
    @ResponseBody
    public AjaxResult getWeekCourses(ApiLoginRequest request)
    {
        AjaxResult res = AjaxResult.success();
        String classId = request.getClassId();
        if(classId!=null){
            ClassInfo classInfo =classInfoService.selectClassInfoById(Long.parseLong(classId));
            if(classInfo!=null){
                Long schoolId = classInfo.getDeptId();
                CourseMainConfigVo conf = new CourseMainConfigVo();
                conf.setBgDate(DateUtils.getNowDate());
                conf.setGradeId(classInfo.getGradeId());
                //后期需要添加学校Id区分各个学校的课程
                conf.setSchoolId(schoolId);
                CourseMainConfigVo mainc = courseMainConfigService.selectCourseMainConfigItem(conf);
                if(mainc!=null){
                    int wk = DateUtils.getWeeksSubByCurr(mainc.getBgDate());
                    int circle = mainc.getWeeks();
                    CourseItemConfigVo item = new CourseItemConfigVo();
                    item.setMainId(mainc.getId());
                    int type = 1;
                    circle = circle==0?1:circle;
                    if(circle != 1){
                        type = wk%circle;
                        if(type==0){
                            type = circle;
                        }
                    }
                    item.setType(type);
                    item.setClazzId(classInfo.getId());
                    List<CourseItemConfigVo> list = courseItemConfigService.selectCourseItemConfigList(item);
                    JSONObject weekCourses = new JSONObject();

                    int sections = mainc.getSections();
                    SysUser user = new SysUser();
                    user.setDeptId(schoolId);
                    List<SysUser> uList = userService.selectUserList(user);
                    if(list!=null){
                        for(int m=1;m<8;m++){
                            List<CourseApiVo> list2 = new ArrayList<>();
                            for(int i=1;i<=sections;i++){
                                CourseApiVo cvo = getCourseInfoBySection2(i,m,list,uList);
                                list2.add(cvo);
                            }
                            String key = "D"+m;
                            weekCourses.put(key,list2);
                        }

                    }else{
                        for(int m=1;m<8;m++){
                            List<CourseApiVo> list2 = new ArrayList<>();
                            for(int i=1;i<=sections;i++){
                                CourseApiVo cvo = getCourseInfoBySection2(i,m,null,uList);
                                list2.add(cvo);
                            }
                            String key = "D"+m;
                            weekCourses.put(key,list2);
                        }

                    }
                    res.put("weekCourse",weekCourses);
                }
                res.put("courseInfo",mainc);
            }
        }else{
            return AjaxResult.error("请重新登陆");
        }
        return res;
    }

    private CourseApiVo getCourseInfoBySection(int i, List<CourseItemConfigVo> list, List<SysUser> uList) {
        CourseApiVo cvo = new CourseApiVo();
        if(list!=null&&list.size()>0){
            for (CourseItemConfigVo item0:list ) {
                if(item0.getSection() == i){
                    cvo.setSection(item0.getSection());
                    SysDictData d0 = findCourseInfo(item0.getCourseId());
                    if(d0!=null){
                        item0.setCourseName(d0.getDictLabel());
                        cvo.setCourseName(d0.getDictLabel());
                    }
                    if(item0.getTeacherId()!=null){
                        SysUser user = findUserInfo(item0.getTeacherId(), uList);
                        if(user!=null){
                            item0.setTeacherName(user.getUserName());
                            cvo.setTeacherName(user.getUserName());
                            cvo.setAvatar(user.getAvatar());
                        }
                    }
                    if(!StringUtils.isEmpty(item0.getBTime())){
                        cvo.setBTime(item0.getBTime());
                        cvo.setETime(item0.getETime());
                        cvo.makeTime();
                    }
//                    return cvo;
                }else{
                    cvo.setSection(i);
                }
            }
        }else{
            cvo.setSection(i);
        }

        return cvo;

    }

    private CourseApiVo getCourseInfoBySection2(int i,int week, List<CourseItemConfigVo> list, List<SysUser> uList) {
        CourseApiVo cvo = new CourseApiVo();
        cvo.setWeek(week);
        if(list!=null&&list.size()>0){
            for (CourseItemConfigVo item0:list ) {
                if(item0.getSection() == i&&item0.getWeek()==week){
                    cvo.setSection(item0.getSection());
                    SysDictData d0 = findCourseInfo(item0.getCourseId());
                    if(d0!=null){
                        item0.setCourseName(d0.getDictLabel());
                        cvo.setCourseName(d0.getDictLabel());
                    }
                    if(item0.getTeacherId()!=null){
                        SysUser user = findUserInfo(item0.getTeacherId(), uList);
                        if(user!=null){
                            item0.setTeacherName(user.getUserName());
                            cvo.setTeacherName(user.getUserName());
                            cvo.setAvatar(user.getAvatar());
                        }
                    }
                    if(!StringUtils.isEmpty(item0.getBTime())){
                        cvo.setBTime(item0.getBTime());
                        cvo.setETime(item0.getETime());
                        cvo.makeTime();
                    }
//                    return cvo;
                }else{
                    cvo.setSection(i);
                }
            }
        }else{
            cvo.setSection(i);
        }
        return cvo;

    }

    @GetMapping("/getExameInfo")
    @ResponseBody
    public AjaxResult getExameInfo(ApiLoginRequest request)
    {
        AjaxResult res = AjaxResult.success();
        String classId = request.getClassId();
        if(classId!=null){
            ClassInfo classInfo =classInfoService.selectClassInfoById(Long.parseLong(classId));
            if(classInfo!=null){
                Long schoolId = classInfo.getDeptId();
                ExamRoomSchedule sche = new ExamRoomSchedule();
                sche.setGradeId(classInfo.getGradeId());
//                sche.setSchoolId(schoolId);
                List<ExamRoomSchedule> list = examRoomScheduleService.selectExamRoomScheduleList(sche);
                if(list!=null){
                    Collections.sort(list,new Comparator<ExamRoomSchedule>(){
//                        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        @Override
                        public int compare(ExamRoomSchedule o1, ExamRoomSchedule o2) {
                            return o1.getExamTime().toString().compareTo(o2.getExamTime().toString());
                        }
                    });
                    int size = list.size();
                    sche = list.get(size-1);
                    ExamRoomClasses classes = new ExamRoomClasses();
                    classes.setScheduleId(sche.getId());
                    classes.setRRid(classInfo.getRoomId());
                    List<ExamRoomClasses> listRoom = examRoomClassesService.selectExamRoomClassesList(classes);
                    if(listRoom!=null&&listRoom.size()>0){
                        ExamRoomStudents student = new ExamRoomStudents();
                        student.setClazzId(listRoom.get(0).getId());
                        student.setScheduleId(sche.getId());
                        List<ExamRoomStudents> listStudents = examRoomStudentsService.selectExamRoomStudentsList(student);
                        res.put("roomStudents",listStudents);
                    }else{
                        res.put("roomStudents",new ArrayList<>());
                    }
                    res.put("exam",sche);
                }
            }
        }else{
            return AjaxResult.error("请重新登陆");
        }
        return res;
    }

    /**
     * 获取考勤记录
     * @param request
     * @return
     */
    @GetMapping("/getClocksRecord")
    @ResponseBody
    public AjaxResult getClocksRecord(ApiLoginRequest request)
    {
        AjaxResult res = AjaxResult.success();
        String classId = request.getClassId();
        if(classId!=null){
            ClassInfo classInfo =classInfoService.selectClassInfoById(Long.parseLong(classId));
            if(classInfo!=null){
                BaseClockInQuery query = new BaseClockInQuery();
                query.setSchoolId(classInfo.getDeptId());
                query.setUserType(2);
                Map<String, Object> params = new HashMap<>();
                params.put("bgDate",DateUtils.getSomeDayStartTime(DateUtils.getNowDate()));
                params.put("edDate",DateUtils.getSomeDayEndTime(DateUtils.getNowDate()));
                params.put("userId",2);
                params.put("classId",classId);
                query.setParams(params);
                //总的打卡数
                List<ClockInReportVo> listAll = clockInRecordService.queryClockInDataClazz(query);

                params.put("status",1);
                query.setParams(params);
                //迟到数
                List<ClockInReportVo> listLate= clockInRecordService.queryClockInDataClazz(query);
                ClassClockApiVo vo = new ClassClockApiVo();
                if(listAll!=null){
                    ClockInReportVo n0 = listAll.get(0);
                    vo.setTotal(n0.getCounts()==null?0:n0.getCounts());
                }
                if(listLate!=null){
                    ClockInReportVo n0 = listLate.get(0);
                    vo.setLateCount(n0.getCounts()==null?0:n0.getCounts());
                }

                Student student = new Student();
                student.setClassId(classInfo.getId());
                List<Student> list = studentService.selectStudentList(student);
                if(list!=null){
                    vo.setStudentCount(list.size());
                }
                ApplyList apply = new ApplyList();
                apply.setClassId(classInfo.getId());
                apply.setStatus(2);//审批通过
                Map<String,Object> pmp = new HashMap<>();
                pmp.put("beginTime",DateUtils.parseDateToStr("YYYY-MM-DD",DateUtils.getNowDate()));
                pmp.put("endTime",DateUtils.parseDateToStr("YYYY-MM-DD",DateUtils.getNowDate()));
                apply.setParams(pmp);
                List<ApplyList> listApply = applyListService.selectApplyListList(apply);
                if(listApply!=null&&listApply.size()>0){
                    vo.setLeaveCount(listApply.size());
                }
                res.put("clockInfo",vo);

            }
        }else{
            return AjaxResult.error("请重新登陆");
        }
        return res;
    }

    /**
     * 获取违规记录
     * @param request
     * @return
     */
    @GetMapping("/getIllegalList")
    @ResponseBody
    public AjaxResult getIllegalList(ApiLoginRequest request)
    {
        AjaxResult res = AjaxResult.success();
        String classId = request.getClassId();
        if(classId!=null){
            ClassInfo classInfo =classInfoService.selectClassInfoById(Long.parseLong(classId));
            if(classInfo!=null){
                IllegalRecordQuery ill = new IllegalRecordQuery();
                ill.setClassId(classInfo.getId());
                List<IllegalRecordVo> list = illegalRecordService.selectIllegalRecordList(ill);
                res.put("iList",list);
            }
        }else{
            return AjaxResult.error("请重新登陆");
        }
        return res;
    }

    /**
     * 获取班级风采
     * 只获取最近的10~20张图片
     * @param request
     * @return
     */
    @GetMapping("/getClazzFc")
    @ResponseBody
    public AjaxResult getClazzFc(ApiLoginRequest request)
    {
        AjaxResult res = AjaxResult.success();
        String classId = request.getClassId();
        if(classId!=null){
            ClassInfo classInfo =classInfoService.selectClassInfoById(Long.parseLong(classId));
            if(classInfo!=null){
                List<ClazzFcApiVo> list = new ArrayList<>();
                if(StringUtils.isEmpty(classInfo.getImg())){
                    ClazzFcApiVo v0 = new ClazzFcApiVo();
                    v0.setImg("http://img-arch.pconline.com.cn/images/upload/upc/tx/photoblog/1304/14/c4/19847253_19847253_1365929410343.jpg");
                    v0.setTitle(classInfo.getClassName()+"---春游1");
                    list.add(v0);
                    ClazzFcApiVo v1 = new ClazzFcApiVo();
                    v1.setImg("http://img-arch.pconline.com.cn/images/upload/upc/tx/photoblog/1304/14/c4/19847059_19847059_1365929031296.jpg");
                    v1.setTitle(classInfo.getClassName()+"---春游2");
                    list.add(v1);
                    ClazzFcApiVo v2 = new ClazzFcApiVo();
                    v2.setImg("http://img-arch.pconline.com.cn/images/upload/upc/tx/photoblog/1304/14/c4/19847059_19847059_1365929018468.jpg");
                    v2.setTitle(classInfo.getClassName()+"---春游3");
                    list.add(v2);
                }else{
                    String imgUris = classInfo.getImg();
                    String img[] = imgUris.split(",");
                    String title = classInfo.getClassName()+"";
                    for(String im :img){
                        if(!StringUtils.isEmpty(im)){
                            ClazzFcApiVo v0 = new ClazzFcApiVo();
                            v0.setImg(im);
                            v0.setTitle(title);
                            list.add(v0);
                        }

                    }
                }
               res.put("clazzFcList",list);
            }
        }else{
            return AjaxResult.error("请重新登陆");
        }
        return res;
    }



    private SysUser findUserInfo(Long uId,List<SysUser> uList){
        SysUser u = null;
        for (SysUser u0:uList
        ) {
            if(u0.getUserId().equals(uId)){
                u = u0;
                break;
            }
        }
        return u;
    }

    public SysDictData findCourseInfo(Integer k){
        List<SysDictData> listDict = dictService.getType("sc_subject_type");
        SysDictData dictData = null;
        for (SysDictData dictData1:listDict){
            if(Integer.parseInt(dictData1.getDictValue())==k){
                dictData = dictData1;
                break;
            }
        }
        return dictData;
    }

    /**
     * 获取老师
     */
    @PostMapping("/getTeacherList")
    @ResponseBody
    public AjaxResult getTeacherList(Long schoolId)
    {
        SysUser user = new SysUser();
        user.setDeptId(schoolId);

        List<SysUser> list = sysUserService.selectUserList(user);
        list = list.stream().sorted((user1, user2) -> {
            Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
            return cmp.compare(user1.getUserName(), user2.getUserName());
        }).collect(Collectors.toList());



        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询老师列表成功",list);

        return res;
    }

    /**
     * 获取课程
     */
    @PostMapping("/getCourseList")
    @ResponseBody
    public AjaxResult getCourseList()
    {

        List<SysDictData> list = this.dictService.getType("sc_subject_type");
        list = list.stream().sorted((dict1, dict2) -> {
            Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
            return cmp.compare(dict1.getDictLabel(), dict2.getDictLabel());
        }).collect(Collectors.toList());



        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询学科列表成功",list);

        return res;
    }

    /**
     * 获取年级
     */
    @PostMapping("/getGradeList")
    @ResponseBody
    public AjaxResult getGradeList(Long schoolId) {

        Grade grade = new Grade();
        grade.setStatus(1);
        grade.setShcoolId(schoolId);
        List<Grade> list = gradeService.selectGradeList(grade);
        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询年级列表成功",list);
        return res;
    }

    /**
     * 获取班级列表
     */
    @PostMapping("/getClassList")
    @ResponseBody
    public AjaxResult getClassList(Long schoolId,Long gradeId) {

        ClassInfo classInfo = new ClassInfo();
        classInfo.setStatus(1);
        classInfo.setDeptId(schoolId);
        classInfo.setGradeId(gradeId);
        List<ClassInfo> list = classInfoService.selectClassInfoList(classInfo);
        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询班级列表成功",list);
        return res;
    }
    /**
     * 获取调课节次
     */
    @PostMapping("/getCourseNoList")
    @ResponseBody
    public AjaxResult getCourseNoList() {

        List<SysDictData> list = this.dictService.getType("sc_course_no");


        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询调课节次列表成功",list);

        return res;
    }

    /**
     * 申请调课
     */
    @PostMapping("/addAdjustCourse")
    @ResponseBody
    public AjaxResult addAdjustCourse(AdjustCourse adjustCourse)
    {
        return toAjax(adjustCourseService.insertAdjustCourseByWechat(adjustCourse));
    }

    /**
     * 申请调课
     */
    @PostMapping("/updateAdjustCourse")
    @ResponseBody
    public AjaxResult updateAdjustCourse(AdjustCourse adjustCourse)
    {

        try {

            return AjaxResult.success(adjustCourseService.updateAdjustCourse(adjustCourse));
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取老师某周的课程表
     * @param clazzId
     * @param teacherId
     * @param beginWeek
     * @param endWeek
     * @return
     */
    @PostMapping("/getWeekClazzCourseInfoByTeacher")
    @ResponseBody
    public Map<String,Object> getClazzCourseInfoTeacher(Long clazzId,Long teacherId,String beginWeek,String endWeek)
    {
        Map<String,Object> res = new HashMap<>();
        List< Map<String,Object>> mapList = new ArrayList<>();
        Map<Integer, List<CourseItemConfigVo>> result = new HashMap<>();
        int bw = Integer.parseInt(beginWeek);
        int ew = Integer.parseInt(endWeek);
        if(bw>ew){
            return res;
        }
        CourseItemConfigVo courseItemConfig = new CourseItemConfigVo();
        Map params = new HashMap();
        params.put("bType",bw);
        params.put("eType",ew);
        courseItemConfig.setParams(params);
        courseItemConfig.setTeacherId(teacherId);

        PersonnelInfo info = personnelInfoService.selectUserById(teacherId);
        //获取当前老师对应的排课信息
        List<CourseItemConfigVo> list = courseItemConfigService.selectCourseItemConfigList(courseItemConfig);


        if(CollectionUtils.isNotEmpty(list)){
            CourseMainConfigVo courseMainConfig = courseMainConfigService.selectCourseMainConfigById(list.get(0).getMainId());
            Map<String,Object> sectionCountMap = new HashMap<>();
            for (int i = 1; i <= courseMainConfig.getSections(); i++) {
                sectionCountMap.put("id",i);
                sectionCountMap.put("time", "第"+ i+"节");
                sectionCountMap.put("name1","");
                sectionCountMap.put("name2","");
                sectionCountMap.put("name3","");
                sectionCountMap.put("name4","");
                sectionCountMap.put("name5","");
                sectionCountMap.put("name6","");
                sectionCountMap.put("name7","");
            }
            res.put("sectionCount",sectionCountMap);
            //按节次分组(每节课一行)
            result = list.stream().collect(Collectors.groupingBy(CourseItemConfigVo::getSection));
            for (Map.Entry<Integer, List<CourseItemConfigVo>> entry : result.entrySet()) {
                Map<String,Object> sectionMap = new HashMap<>();
                sectionMap.put("section",entry.getKey());
                sectionMap.put("data",entry.getValue());
                mapList.add(sectionMap);
            }
            res.put("dataList",mapList);
        }
        log.info("获取老师课表:{}", JSON.toJSONString(mapList));
        return res;
    }

    private List<JSONObject> getBaseJsonData(int nodes) {
        List<JSONObject> datas = new ArrayList<>();
        for (int i = 1; i <= nodes; i++) {
            JSONObject j0 = new JSONObject();
            j0.put("section", i);
            for (int k = 1; k < 8; k++) {
                j0.put("w" + k, "");
            }
            datas.add(j0);
        }
        return datas;
    }


    /**
     * 保存考勤记录
     * @param deviceNo 设备号
     * @param cardNo 卡号
     * @param deviceTime 设备上打卡时间
     * @param inOutFlag 进出标志 01表示校外，02表示校内
     * @return
     */
    @GetMapping("/saveAttendance")
    @ResponseBody
    public AjaxResult saveAttendance(String deviceNo,String cardNo,String deviceTime,String inOutFlag)
    {
        logger.info("打卡记录：-------------------->deviceNo=" + deviceNo + "&cardNo=" + cardNo + "&deviceTime=" + deviceTime + "&inOutFlag=" + inOutFlag);

        if("0".equals(deviceNo) || "0000000000".equals(cardNo)){
            return success();
        }
        setClockData(deviceNo,cardNo,deviceTime,inOutFlag);


        return success();
    }

    /**
     * 设置考勤记录
     * @param deviceNo
     * @param cardNo
     * @param deviceTime
     * @param inOutFlag
     */
    private  void setClockData(String deviceNo,String cardNo,String deviceTime,String inOutFlag){
        //0000000000 无效卡号 心跳数据
        //获取学校编号
        String schoolNo = "1001";//deviceNo.substring(0,3);
        ScBadge query = new ScBadge();
        query.setBadgeNo(cardNo);
        query.setScId(118L);
        List<ScBadge> badgeList = badgeService.selectScBadgeList(query);
        if(CollectionUtils.isNotEmpty(badgeList)){
            //插入打卡记录
            ScBadge scBadge = badgeList.get(0);
            AttendanceRecord record = new AttendanceRecord();
            record.setCardNo(scBadge.getBadgeNo());
            record.setDeviceNo(deviceNo);
            record.setSchoolId(118L);
            record.setCreateTime(DateUtils.dateTime("yyyyMMddHHmmss",deviceTime));
            attendanceRecordService.insertAttendanceRecord(record);
        SchoolExt ext = new SchoolExt();
        ext.setSchoolCode(schoolNo);
        List<SchoolExt> schoolExtList = schoolExtService.selectSchoolExtList(ext);
        if(CollectionUtils.isNotEmpty(schoolExtList)){
           // String deviceCode = deviceNo.substring(3,6);
          //  Long schoolId = schoolExtList.get(0).getSchoolId();//

               /* //考勤状态
                boolean isCome = SchoolUtil.isCome(Integer.parseInt(deviceCode));

                ScBadge scBadge = badgeList.get(0);
                //查询当天打卡记录
                ClockInRecord queryParams = new ClockInRecord();
                queryParams.setBadgeNo(cardNo);
                Map<String,Object> dateParam = new HashMap<>();
                dateParam.put("beginClockTime",DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,DateUtils.getCurrentDayStartTime()));
                dateParam.put("endClockTime",DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,DateUtils.getCurrentDayEndTime()));
                queryParams.setParams(dateParam);
                List<ClockInRecord> clockInRecordList = clockInRecordService.selectClockInRecordList(queryParams);

                if(CollectionUtils.isNotEmpty(clockInRecordList)){
                    boolean isOut = !SchoolUtil.isCome(clockInRecordList.size());
                    //如果有打卡记录，判断最后一次打卡时间
                    ClockInRecord last = clockInRecordList.get(clockInRecordList.size()-1);
                    //如果最后一次打卡时间是中午12点之前,并且本次是进入的，就不再记录
                    if(last.getClockTime().before(DateUtils.parseDate(DateUtils.getDate()+" "+SchoolUtil.morningEndTime))
                      && isCome && !isOut){
                        return;
                    }
                    //如果最后一次打卡时间是中午12点之前,并且不是离校记录,并且本次是出去的（中午放学）
                    if(last.getClockTime().before(DateUtils.parseDate(DateUtils.getDate()+" "+SchoolUtil.morningEndTime))
                            && !isCome && !isOut){
                        log.info("cardNo{}中午放学打卡:{}",cardNo,deviceTime);
                        Long min = -DateUtils.getDatePoorByStringTime(SchoolUtil.morningEndTime,deviceTime);
                        saveClockInRecord(schoolId,cardNo,deviceTime,scBadge,min,isCome);
                    }
                    //如果最后一次打卡时间是8点之后,且是离校记录,并且本次是进来的（下午返校）
                    if(last.getClockTime().after(DateUtils.parseDate(DateUtils.getDate()+" "+SchoolUtil.morningBeginTime))
                            && isCome && isOut){
                        log.info("cardNo{}下午返校打卡:{}",cardNo,deviceTime);
                        Long min = DateUtils.getDatePoorByStringTime(SchoolUtil.noonBeginTime,deviceTime);
                        saveClockInRecord(schoolId,cardNo,deviceTime,scBadge,min,isCome);
                    }
                    //如果最后一次打卡时间是下午12点之后,6点之前,且不是离校记录，说明下午还没有离校
                    if(last.getClockTime().after(DateUtils.parseDate(DateUtils.getDate()+" "+SchoolUtil.morningEndTime))
                        && last.getClockTime().before(DateUtils.parseDate(DateUtils.getDate()+" "+SchoolUtil.noonEndTime))
                            && !isCome && !isOut){
                        log.info("cardNo{}下午放学打卡:{}",cardNo,deviceTime);
                        Long min = -DateUtils.getDatePoorByStringTime(SchoolUtil.noonEndTime,deviceTime);
                        saveClockInRecord(schoolId,cardNo,deviceTime,scBadge,min,isCome);
                    }

                }else {
                    //早上第一次打卡
                    log.info("cardNo{}早上第一次打卡:{}",cardNo,deviceTime);
                    Long min = DateUtils.getDatePoorByStringTime(SchoolUtil.morningBeginTime,deviceTime);
                    saveClockInRecord(schoolId,cardNo,deviceTime,scBadge,min,isCome);
                }*/

            }
        }

    }

    /**
     * 保存打卡记录
     * @param schoolId
     * @param cardNo
     * @param deviceTime
     * @param scBadge
     * @param min
     */
    private void saveClockInRecord(Long schoolId,String cardNo,String deviceTime,ScBadge scBadge,Long min,boolean isCome){
        ClockInRecord clockInRecord = new ClockInRecord();
        clockInRecord.setSchoolId(schoolId);
        clockInRecord.setBadgeNo(cardNo);
        clockInRecord.setClockTime(DateUtils.parseDate(deviceTime));
        clockInRecord.setStatus(0);
        if(isCome && min < 0){
            clockInRecord.setStatus(1);
        }

        if(!isCome && min < 0){
            clockInRecord.setStatus(2);
        }

        clockInRecord.setUserNo(scBadge.getUserNo());
        clockInRecord.setUserType(scBadge.getUserType());
        clockInRecord.setUserId(scBadge.getUserId());
        clockInRecord.setUserName(scBadge.getUserName());
        clockInRecord.setInOutMinute(Math.abs(min.intValue()));
        clockInRecordService.insertClockInRecord(clockInRecord);
    }

    /***
     * 名言警句
     * @param request
     * @return
     */
    @GetMapping("/getClazzWis")
    @ResponseBody
    public AjaxResult getClazzWis(ApiLoginRequest request)
    {
        AjaxResult res = AjaxResult.success();
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(request.getClassId()))
        {
            return AjaxResult.error("班级编号或密码为空");
        }
        String classId = request.getClassId();
        ClassInfo classInfo =classInfoService.selectClassInfoById(Long.parseLong(classId));
        if(classInfo!=null){
            Wisdom wiItem = new Wisdom();
            wiItem.setClassId(classInfo.getId());
            List<Wisdom> wisdomList = wisdomService.selectWisdomList(wiItem);
            if(wisdomList!=null&&!wisdomList.isEmpty()){
                res.put("wList",wisdomList);
            }else{
                res.put("wList",new ArrayList<>());
            }
        }
        return res;
    }

    /**
     * 班委组成
     * @param request
     * @return
     */
    @GetMapping("/getClassComm")
    @ResponseBody
    public AjaxResult getClassComm(ApiLoginRequest request)
    {
        AjaxResult res = AjaxResult.success();
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(request.getClassId()))
        {
            return AjaxResult.error("班级编号或密码为空");
        }
        String classId = request.getClassId();
        ClassInfo classInfo =classInfoService.selectClassInfoById(Long.parseLong(classId));
        if(classInfo!=null){
            List<JSONObject> bwList = new ArrayList<>();//班委

            res.put("clazzManagers",bwList);
            List<JSONObject> dbList = new ArrayList<>();//课代表
            res.put("courseUsers",dbList);
            List<JSONObject> groupList = new ArrayList<>();//组长
            res.put("groupList",groupList);
        }
        return res;
    }

    /**
     * 班委组成
     * @param request
     * @return
     */
    @GetMapping("/getVersionInfo")
    @ResponseBody
    public AjaxResult getVersionInfo(ApiLoginRequest request)
    {
        AjaxResult res = AjaxResult.success();
        AppVersion appVersion = appVersionService.getLastVersion();
        // 用户名或密码为空 错误
        JSONObject json = new JSONObject();
        if(appVersion != null){
            json.put("version",appVersion.getVersion());
            json.put("dir",appVersion.getUrl());
        }else {
            json.put("version","1");
            json.put("dir","");
        }

        res.put("data",json);
        return res;
    }

    /**
     * 微信端获取app配置
     * @return
     */
    @GetMapping("/getBannerList")
    @ResponseBody
    public AjaxResult getBannerList(Integer type)
    {
        AppConfig config = new AppConfig();
        config.setType(type);
        List<AppConfig> list = appConfigService.selectAppConfigListBySort(config);

        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询app配置成功",list);

        return res;
    }
    public static void main(String[] args) {
        //
        System.out.println(DateUtils.dateTime("yyyyMMddHHmmss","20201130201235"));
    }


    @GetMapping("/send")
    public String send(String appid){
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        //wxService.getMsgService().sendUniformMsg();
        return "ok";
    }


    @GetMapping("/download")
    public String download(){
        AppVersion appVersion = appVersionService.getLastVersion();
        return appVersion.getUrl();
    }

    @GetMapping("/getClazzComm")
    @ResponseBody
    public AjaxResult getClazzComm(ApiLoginRequest request)
    {
        AjaxResult res = AjaxResult.success();
        String classId = request.getClassId();
        if(classId!=null){
            ClassInfo classInfo = classInfoService.selectClassInfoById(Long.parseLong(classId));
            if(classInfo!=null){

                CalzzCommittee czz = new CalzzCommittee();
                czz.setType(1);
                czz.setClazzId(classInfo.getId());
                List<CalzzCommittee> bwjg = calzzCommitteeService.selectCalzzCommitteeList(czz);
//                List<JSONObject> bwjg = getClazzBw(classInfo.getId());
                res.put("bwjg",bwjg);
                CalzzCommittee czz2 = new CalzzCommittee();
                czz2.setType(2);
                czz2.setClazzId(classInfo.getId());
                List<CalzzCommittee> kdbList = calzzCommitteeService.selectCalzzCommitteeList(czz2);
//                List<JSONObject> kdbList = getClazzKDB(classInfo.getId());
                res.put("kdb",kdbList);
                List<JSONObject> groups = new ArrayList<>();

                //获取当前值日表
                JSONObject workGroup = new JSONObject();
                //获取值日表
                this.getDutyTable(request,groups,workGroup);
                res.put("groupsInfo",groups);
                res.put("workInfo",workGroup);
            }
        }else{
            return AjaxResult.error("请重新登陆");
        }
        return res;
    }

    private List<JSONObject> getClazzKDB(Long clazzId) {
        List<JSONObject> bwjg = new ArrayList<>();
        JSONObject j1 = new JSONObject();
        j1.put("titleName","语文");
        j1.put("userName","扬国威");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","英语");
        j1.put("userName","程丽丽、彩雅悯");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","数学");
        j1.put("userName","韩雪云");

        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","政治");
        j1.put("userName","彩雅悯");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","生物");
        j1.put("userName","吴婷邴");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","历史");
        j1.put("userName","黄珊珊");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","地理");
        j1.put("userName","潘  林");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","体育");
        j1.put("userName","李刚");
        bwjg.add(j1);
        return bwjg;
    }
    private List<JSONObject> getClazzBw(Long clazzId) {
        List<JSONObject> bwjg = new ArrayList<>();
        JSONObject j1 = new JSONObject();
        j1.put("titleName","班长");
        j1.put("userName","扬国威");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","副班长");
        j1.put("userName","程丽丽");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","团支部书记");
        j1.put("userName","韩雪云");

        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","纪律委员");
        j1.put("userName","彩雅悯");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","学习委员");
        j1.put("userName","吴婷邴");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","生活委员");
        j1.put("userName","黄珊珊");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","宣传委员");
        j1.put("userName","潘  林");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","体育委员");
        j1.put("userName","李刚");
        bwjg.add(j1);
        j1 = new JSONObject();
        j1.put("titleName","文娱委员");
        j1.put("userName","李睿茵");
        bwjg.add(j1);
        return bwjg;
    }


    /**
     * 值日表
     * @param request
     * @return
     */
    private List<DutyTable> getDutyTable(ApiLoginRequest request,List<JSONObject> groups,JSONObject workGroup)
    {
        DutyTable dutyTable = new DutyTable();
        dutyTable.setClassId(Long.valueOf(request.getClassId()));
        List<DutyTable> dutyTableList = dutyTableService.selectDutyTableList(dutyTable);
        int week = DateUtils.getCurrWeerk();
        if(CollectionUtils.isNotEmpty(dutyTableList)){
            //按星期排序
            Collections.sort(dutyTableList,new Comparator<DutyTable>(){
                @Override
                public int compare(DutyTable o1, DutyTable o2) {
                    int diff = o1.getWeekDay().intValue() - o2.getWeekDay().intValue();
                    if (diff > 0) {
                        return 1;
                    }else if (diff < 0) {
                        return -1;
                    }
                    return 0; //相等为0
                }
            });
            List<Student> students = studentService.getStudentByClassIdList(Lists.newArrayList(dutyTable.getClassId()));
            Map<Long,Student> map = students.stream().collect(Collectors.toMap(student-> student.getId(),s->s));

            for (DutyTable table : dutyTableList) {
                String[] memberIds = table.getMembersIds().split(",");
                StringBuilder membersNames = new StringBuilder("");
                for (String memberId : memberIds) {
                    membersNames.append(map.get(Long.valueOf(memberId)).getStudentName() +" ");
                }
                table.setLeaderName(map.get(table.getLeaderId()).getStudentName());
                table.setMembersNames(membersNames.toString());
                table.setWeekDayName(dictService.getLabel("sc_week_day",table.getWeekDay().toString()));

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("titleName",table.getWeekDayName());
                jsonObject.put("userName",table.getLeaderName());
                groups.add(jsonObject);
                if(week == table.getWeekDay()){
                    workGroup.put("groupLeader",table.getLeaderName());
                    workGroup.put("groupPersons",table.getMembersNames());
                }
            }

        }
        return dutyTableList;
    }

}
